﻿
using Curry.Forum.Command.Domain.Service;
using Curry.Forum.Command.Handler.AutoFac;
using Curry.Forum.Command.Handler.AutoMapper.Map;
using Curry.Forum.Facade.Core.Request;
using Newtonsoft.Json;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Curry.Forum.Command.Handler.Command
{
    public class ArticleCommandApp
    {
        const string TopExchangeName = "topic.test.exchange";
        const string TopQueueName = "topic.test.queue";

        private ArticleService _articleService;
        public ArticleCommandApp(ArticleService articleService)
        {
            _articleService = articleService;
        }

        public void CreateArticleModel(string msg)
        {
            var articleRequest = JsonConvert.DeserializeObject<ArticleInfoRq>(msg);

            var request = AutofacExt.GetFromFac<IMapRequest>().ArticleMap(articleRequest);

            if(request.Author!=null)
                _articleService.CreateArticleModel(request);
        }

        public bool Create(ArticleInfoRq article)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(article.Author))
                {
                    return false;
                }
                using (var conn = new Helper.MqHelper().GetConnection())
                {
                    using (IModel channel = conn.CreateModel())
                    {
                        channel.ExchangeDeclare(TopExchangeName, "topic", false, false, null);
                        channel.QueueDeclare(TopQueueName, false, false, false, null);
                        channel.QueueBind(TopQueueName, TopExchangeName, TopQueueName);

                        var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(article));

                        channel.BasicPublish(TopExchangeName, TopQueueName, null, body);
                    }
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
